// 引入axios
import router from '@/router';
import { useUserStore } from '@/stores/modules/user';
import axios, { AxiosError } from 'axios';
//xxxxxxxx const userStore = useUserStore(); // 热乎的 现用现造
//创建请求
const instance = axios.create({
  baseURL: 'https://consult-api.itheima.net',
  timeout: 1000 * 10
});
//请求拦截器
instance.interceptors.request.use(
  (config) => {
    const userStore = useUserStore();
    if (userStore.user?.token) {
      config.headers['Authorization'] = `Bearer ${userStore.user.token}`;
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);
instance.interceptors.response.use(
  (res) => {
    if (res.data.code !== 10000) {
      return Promise.reject(res.data);
    }
    return res.data;
  },
  (err: AxiosError) => {
    // 处理401错误
    if (err.response?.status === 401) {
      // token无效 校验失败:跳转到登录页
      // 删除用户信息 跳转到登录页
      const userStore = useUserStore();
      userStore.delUser();
      router.push({
        path: '/login',
        query: {
          redirectURL: router.currentRoute.value.fullPath
        }
      });
    }
    return Promise.reject(err);
  }
);

export default instance;
